﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CoreLib.MySQL.Mapping;

namespace CoreLib.MySQL.Mapping
{
    /// <summary>
    /// Attribute used to define a new column linked to the target
    /// property/field
    /// </summary>
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
    public class DbFieldAttribute : Attribute
    {
        /// <summary>
        /// Defines if the numeric column will be incremented by '1' when a 
        /// new row is created. Default = false
        /// </summary>
        public bool AutoIncrement = false;
        /// <summary>
        /// Sets a default value for the column
        /// </summary>
        public object Default = null;
        /// <summary>
        /// Defines if the column will allow null values
        /// </summary>
        public bool Nullable = true;
        /// <summary>
        /// Defines if the column will be primary key
        /// </summary>
        public bool IsPrimaryKey = false;
        /// <summary>
        /// Sets the column name
        /// </summary>
        internal string ColumnName { get; set; }
        /// <summary>
        /// Gets the Type of the variable owner of this attribute
        /// </summary>
        internal Type VariableType { get; set; }

        //for Object quering purposes
        internal object memberInClass;
        internal bool isProperty = false;

        public DbFieldAttribute(string fieldName)
        {
            this.ColumnName = fieldName;
        }

        public override string ToString()
        {
            StringBuilder columnBuilder = new StringBuilder();
            columnBuilder.AppendFormat("`{0}` ", this.ColumnName);
            columnBuilder.Append(TypeTranslator.TranslateToMySql(this.VariableType));

            if (this.Nullable)
            {
                columnBuilder.Append(" NULL");
            }
            else
            {
                columnBuilder.Append(" NOT NULL");
            }
            if (this.Default != null && !
                TypeTranslator.TranslateToMySql(VariableType).Contains("text"))
            {
                columnBuilder.Append(" default ");
                columnBuilder.AppendFormat("'{0}'", this.Default);
                columnBuilder.Replace("True", "1");
                columnBuilder.Replace("False", "0");
            }
            if (this.AutoIncrement)
            {
                columnBuilder.Append(" AUTO_INCREMENT");
            }

            return columnBuilder.ToString();
        }
    }
}
